#!/bin/sh
##########################################################################
# FileName	: do-insert-disk.sh
# Author	: fanxiaoguang
# Data		: 2016/08/16
# Description	: when inster a disk,  if it is a old osd disk, just 
#		  activate this osd, if it is a new disk create a new osd
# Args		: $1 disk char (like sda ,sdb, or sdc...etc)
#########################################################################

log_file="/var/log/ceph/insert-osd.log"

function is_a_new_disk()
{ 
	osd_disk=$1

	parted /dev/${osd_disk} print | grep ceph | grep journal
	ret_j=$?
	parted /dev/${osd_disk} print | grep ceph | grep data
	ret_d=$?
	if [ ${ret_j} == 0 -a ${ret_d} == 0 ] ;then
		#old disk with ceph partition
		return 1
	else
		# new disk
		return 0
	fi
	
}

function  is_boot_disk()
{    
     disk=$1
	 parted /dev/${disk} print | grep boot
	 ret=$?
	 if [ $ret == 0 ] ; then
	    return 1
	 else 
	    return 0
	 fi
	 
}

function create_new_osd()
{
	osd_disk=$1
	cp -rf /etc/ceph/*.keyring /usr/local/zabbix/
	echo "create a new osd disk: $osd_disk" >> $log_file
	cd  /home/ceph-deploy.d/
	systemctl restart systemd-udevd.service
        echo "sgdisk -o ${osd_disk} " >>  $log_file
        sgdisk -o ${osd_disk}
         
        ceph-deploy  disk zap  `hostname`:/dev/${osd_disk}

        echo "ceph-deploy --overwrite-conf --ceph-conf /etc/ceph/ceph.conf  osd prepare `hostname`:/dev/${osd_disk}" >>$log_file
	ceph-deploy --overwrite-conf --ceph-conf /etc/ceph/ceph.conf  osd prepare `hostname`:/dev/${osd_disk}
	ret=$?
        echo "execute cmd ceph-deploy --overwrite-conf --ceph-conf /etc/ceph/ceph.conf  osd prepare `hostname`:/dev/${osd_disk} "
	echo "ret= $ret" >> $log_file

	ceph-deploy --overwrite-conf --ceph-conf /etc/ceph/ceph.conf  osd activate `hostname`:/dev/${osd_disk}1
	ret=$?
	echo "execute cmd ceph-deploy --overwrite-conf --ceph-conf /etc/ceph/ceph.conf  osd activate `hostname`:/dev/${osd_disk}1" >>$log_file
	echo "ret = $ret" >> $log_file
	return 0;
}

function start_old_osd()
{
	disk_1=$1
	echo "start an old osd: $disk_1" >> $log_file
	systemctl daemon-reload
	systemctl restart systemd-udevd.service
	ceph-disk activate /dev/${disk_1}1
	return 0
}

function main()
{	
        
	echo "date: `date`......................................" >>  $log_file
	osd_disk=`echo $1|grep "disk.status\["|grep "onlien\]"|awk -F '[' '{print $2}'|awk -F ',' '{print $1}'`
	echo "input disk: $osd_disk " >> $log_file
	#check if is boost disk, skip it
	is_boot_disk $osd_disk
	ret=$?
	if [ $ret -eq 1 ]; then
	    echo "$osd_disk is boot disk" >> $log_file
		return 0;
	else
	    echo "$osd_disk is not boot disk" >> $log_file
	fi
	
	is_a_new_disk $osd_disk
	ret=$?
	if [ $ret -eq 1 ]; then
		echo "A old disk: $osd_disk, just start ceph-osd service" >> $log_file
		start_old_osd $osd_disk
	else
		echo "Is a new disk: $osd_disk,  create a new osd now" >> $log_file
		create_new_osd $osd_disk
	fi

}

main $1
